<template>
  <section class="bg-default video-page">
    <section class="no-shadow video-page-content">
      <div class="video">
        <div class="inner" id="videoPlayer">

        </div>
<!--        <video v-if=" detail.files.length>0" :style="{height:'100%'}" :poster="getPoster(preData)" loop="loop" :src="getVideoSrc(detail)" preload="auto" controls autoplay="autoplay" x5-video-player-type="h5-page"></video>-->
      </div>
    </section>
    <section  class="introduce">
      <div v-if="contents" class="content" v-html="detail.newsContentExt.contents">
      </div>
    </section>
  </section>
</template>

<script>
  import _ from 'lodash'
  import Player from 'xgplayer'
  import domUtils from '@/utils/domUtils'

  let TEST = true // 测试 阿里播放器
  export default {
    name: 'videoDetail',
    data() {
      return {
        preData: {},
        audioList: [],
        isVideo: true,
        contents:false,
        clickPlay: false,
        shareType: 1,
        detail: {}
      }
    },
    created() {
      this.init()
    },
    beforeDestroy() {
      clearInterval(this.checkPlayerTimer)
    },
    methods: {
      init() {
        if (this.$route.query.zhuanji !== 1) {
          this.$store.state.zhuanjiList = []
        }
        this.isVideo = this.$store.state.isVideo
        // 0:新闻，1:视频；6:音频
        this.shareType = this.isVideo ? 1 : 6
        this.$store.state.flagType = 2
        this.preData = this.$store.state.videoDetail
        console.log('preData', this.preData)
        this.loadData()
        this.updateCount()
        if (!this.isVideo) {
          this.audioList = this.$store.state.zhuanjiList
          window.audioPlayer.hide()
        } else {
          window.audioPlayer.pause()
        }
      },
      /*专辑播放音乐*/
      playAudio(item) {
        console.log('playAudio')
        if (!this.isVideo) {
          this.$store.state.zhuanjiList = JSON.parse(JSON.stringify(this.$store.state.zhuanjiList))
        }
        this.clickPlay = true
        this.$store.state.videoDetail = item
        let routeName = this.$route.name
        this.$router.replace({name: routeName, query: {id: item.id, zhuanji: 1}})
        this.init()
      },
      /*播放下一首*/
      playAudioNext() {
        clearTimeout(this.$refs.myAudio.playAudioNextTimer)
        this.$refs.myAudio.playAudioNextTimer = setTimeout(() => {
          let playingIndex = this.audioList.findIndex(item => {
            return item.id === this.preData.id
          })
          let nextIndex = playingIndex + 1
          console.log('playAudioNext', nextIndex)
          if (nextIndex >= this.audioList.length) {
            nextIndex = 0
          }
          this.playAudio(this.audioList[nextIndex])
        }, 1000)
      },
      /*视频播放完成*/
      onended() {
        if (!this.isVideo) {
          return this.audioEnded()
        }
        console.log('ended')
        // this.$refs.scoreInstance.getScore('watch')
      },
      listenAudio() {
        // 如果是选择播放，监听事件不必反复执行
        if (this.clickPlay) {
          return false
        }
        this.clickPlay = true
        if (!this.isVideo) {
          this.$refs.myAudio.onended = () => {
            console.log('audio ended')
            this.onended()
          }
          let myAudio = document.getElementById('myAudio')
          myAudio.addEventListener('ended', () => {
            console.log('audio ended')
            this.onended()
          })
          myAudio.addEventListener('timeupdate', (e) => {
            console.log('timeupdate')
            if (myAudio.duration <= myAudio.currentTime + 0.5) {
              console.log('audio ended timeupdate')
              console.log(e)
              return this.onended()
            }
            this.$store.state.audioCurrentTime = myAudio.currentTime
          })
          myAudio.addEventListener('pause', (e) => {
            console.log('pause')
            this.$store.state.isAudioPause = true
            setTimeout(() => {
              if (this.$route.name === 'videoDetail') {
                window.audioPlayer.back()
              }
            }, 10)
          })
          myAudio.addEventListener('play', (e) => {
            console.log('audio play')
            this.$store.state.isAudioPause = false
            this.showAudio()
          })
        }
      },
      showAudio() {
        console.log('showAudio')
        window.audioPlayer.setUrl(this.getVideoSrc(this.detail))
        window.audioPlayer.setContentId(this.detail.newsContent.id)
        window.audioPlayer.setTitle(this.preData.title)
        setTimeout(() => {
          let myAudio = document.getElementById('myAudio')
          myAudio.play()
          this.listenAudio()
        }, 1000)
      },
      getPoster(item) {
        return this.tools.getImgUrl(item.newsContent && item.newsContent.listPic)
      },
      getVideoSrc(item) {
        if (item.newsContent && item.newsContent.videoUrl && item.newsContent.videoUrl !== '') {
          return item.newsContent.videoUrl
        }
        return this.tools.getImgUrl(item.files && item.files[0].fileId)
      },

      updateCount() {
        let id = this.preData.id
        let params = {
          contentId: id,
          type: 1
        }
        this.fetchService.updateCount(params).then(res => {
          if (res.code !== 0) {
            return false
          }
        })
      },
      loadData() {
        let id = this.$store.state.id
        this.fetchService.contentPageDetail(id).then(res => {
          if (res.code !== 0) {
            return false
          }
          this.detail = res.data
          this.contents = true
          this.$store.state.newsDetail = _.extend(this.$store.state.newsDetail, this.detail.newsContent)
          this.$store.state.newsDetail.detail = this.detail
//          ++this.$store.state.newsDetail.views
          this.play(this.detail)
          this.addViews(id)
        })
      },
      addViews(id) {
        this.audioList.findIndex(item => {
          if (item.id === id) {
            ++item.views
          }
        })
      },
      /*阿里播放器*/
      aliplay(data) {
        var player = new Aliplayer({
          id: 'videoPlayer',
          source: this.getVideoSrc(data),
          preload: true,
          autoplay: true,
          rePlay: true,
          controlBarVisibility: 'click',
          showBarTime: '3000',
          x5_type: 'h5',
          x5_fullscreen: true,
          height: '100%'
        }, 
        function (player) {
          player.play()
        }
        );
        $('.prism-error-operation').hide();
        $('.prism-error-content p').hide();
        $('.prism-error-content').append('<p style="margin-top: 50px;">播放出错啦！</p>');
        this.videoPlayerEvent(player)
      },
      play(data) {
        let me = this
        let id = this.$store.state.id
        if (this.$store.state.isVideo) {
          if (TEST) {
            this.aliplay(data)
            return
          }
          let player = new Player({
            id: 'videoPlayer',
            url: this.getVideoSrc(data),
            autoplay: true,
            fluid: true,
            rotate: {   //视频旋转按钮配置项
              innerRotate: true, //只旋转内部video
              clockwise: false // 旋转方向是否为顺时针
            },
            poster: this.getPoster(data)
          })
          player.back = function (type) {
            if (type === undefined) {
              player.exitFullscreen()
            } else if (type === 'exitFullscreen') {
              // 通过事件退出
            }
            if (me.isFullScreen) {
              me.isFullScreen = false
              player.rotate(true, true, -1)
            }
            if (me.tools.getDialogNum() > 0) {
              me.tools.dialog(-1)
            }
            if (me.tools.getDialogNum() <= 0) {
              me.tools.dialogDestroy()
            }
          }
          player.on('ended', () => {
            console.log('video ended')
            this.onended()
            this.$localStorage.set('videoPlayTime' + id, 0)
          })
          player.on('requestFullscreen', () => {
            player.rotate(true, true, 1)
            console.log('video requestFullscreen')
            this.tools.dialog(1, player)
          })
          player.on('exitFullscreen', () => {
            console.log('video ')
            player.back('exitFuexitFullscreenllscreen')
          })
          player.on('rotate', (deg) => {
            this.rotateDeg = deg
            console.log(deg)
          })
          player.on('play', () => {
            let videoPlayTime = this.$localStorage.get('videoPlayTime' + id)
            console.log('play', videoPlayTime, player.currentTime)
            if (videoPlayTime) {
              player.currentTime = videoPlayTime
            }
          })
          // 检查是否全屏
          function checkFullScreen() {
            let playerDom = document.getElementById('videoPlayer')
            if (domUtils.hasClass(playerDom, 'xgplayer-is-fullscreen')) {
              onFullScreen()
              if (!domUtils.hasStyle(document.getElementsByTagName('video')[0], 'rotate(0.25turn')) {
                player.rotate(true, true, 1)
              }
            } else {
              if (!domUtils.hasStyle(document.getElementsByTagName('video')[0], 'rotate(0turn)')) {
                player.rotate(true, true, -1)
              }
            }
          }
          this.checkPlayerTimer = setInterval(checkFullScreen, 500)
          // 固定是否有
          // 全屏标记
          let me = this
          function onFullScreen() {
            if (me.tools.getDialogNum() <= 0) {
              this.tools.dialog(1, player)
              me.isFullScreen = true
            }
          }

          let consoleTime = Date.now()
          player.on('timeupdate', () => {
            if (Date.now() - consoleTime > 3 * 1000) {
              console.log('timeupdate', player.currentTime)
              consoleTime = Date.now()
              this.$localStorage.set('videoPlayTime' + id, player.currentTime)
            }
          })
        }
      },
      /*阿里播放的事件、方法*/
      videoPlayerEvent(player) {
        let me = this
        let id = this.$store.state.id
        player.on('ended', () => {
          console.log('video ended')
          this.onended()
          this.$localStorage.set('videoPlayTime' + id, 0)
        })
        player.on('requestFullscreen', () => {
          player.rotate(true, true, 1)
          console.log('video requestFullscreen')
          this.tools.dialog(1, player)
        })
        player.on('exitFullscreen', () => {
          console.log('video ')
          player.back('exitFuexitFullscreenllscreen')
        })
        player.on('rotate', (deg) => {
          this.rotateDeg = deg
          console.log(deg)
        })
        player.on('play', () => {
          let videoPlayTime = this.$localStorage.get('videoPlayTime' + id)
          console.log('play', videoPlayTime, player.getCurrentTime())
          if (videoPlayTime) {
            player.seek(videoPlayTime)
          }
        })
        let consoleTime = Date.now()
        player.on('timeupdate', () => {
          if (Date.now() - consoleTime > 3 * 1000) {
            console.log('timeupdate', player.getCurrentTime())
            consoleTime = Date.now()
            this.$localStorage.set('videoPlayTime' + id, player.getCurrentTime())
          }
        })
        player.on('requestFullScreen', () => {
          console.log("---------------------requestFullScreen--------")
          if (!window.webkit) {
            console.log('requestFullScreen')
            if (window.android && window.android.screenToggle) {
              window.android.screenToggle(1)
            }
          }
          console.log(this.$router)
          this.$store.state.hasFullScreen = true
          this.$router.options.routes.forEach(v => {
            if (v.name === 'redCloudHeadline') {
              v.meta.keepAlive = true
            }
          })
        })
        player.on('cancelFullScreen', () => {
          console.log("---------------------cancelFullScreen--------")
          if (window.android && window.android.screenToggle) {
            window.android.screenToggle(2)
          }
          try {
            let className = document.querySelector('#videoPlayer').className
            className = className.replace(/\svideo-player/g, '')
            document.querySelector('#videoPlayer').className = className
          } catch (e) {
            console.log('报错：' + e)
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .video-page {
    position: relative;

    .header-wrap-wrap {
      position: absolute;
      z-index: 1;
    }
  }

  .introduce {
    width: 100%;
    height: 250PX;
    margin-bottom: 10%;
    .content {
      padding: 0.13333rem;
      font-size: 16PX;
      text-indent: 2em;
      white-space: normal;
      word-break: break-all;
      text-align: justify;
      margin-top: 5%;
      margin-left: 1%;
      overflow-y: auto;
      overflow-x: auto;
      width: 100%;
      height: 100%;
    }
  }

  .video {
    position: relative;
    z-index: 0;
    height: 420px;
    text-align: center;
    background: #000;

    video {
      width: 88vw;
      /*width:100%;*/
      height: 100%;
      margin: 0 auto;
    }
  }

  .water-logo {
    text-align: center;
    padding: 50px;

    img {
      opacity: .6;
    }
  }
</style>
